<!-- 首页 -->
<template>
	<view class="container">
		<view class="header padding padding-tb-sm bg-white">
			<view class="flex justify-between align-center" :style="{'padding-top':menuHeight+'px'}">
				<!-- 	<view class="">
					<text class="text-bold text-lg">资源监控</text>
				</view> -->
				<view class="" @click="handleOpenPondSelect">
					<view class="flex justify-end align-center">
						<text
							class="text-bold text-xl padding-right-sm text-blue">{{pondSelect.culturePondName || '-'}}</text>
						<van-icon name="arrow-down" />
					</view>
					<view class="text-sm text-right">
						<text></text>
						<text>{{baseInfo.name}}</text>
					</view>
				</view>
			</view>

		</view>

		<view class="" v-if="cameraList.length>0">
			<!-- <live-player ref='player' class="full-width" mode="live" 
			:src="cameraList[cameraIndex].url" 
			:minCache="0.2"
			:maxCache="0.8"
			autoplay @statechange="statechange"
			></live-player> -->
			<video ref='player' 
			id="player"
			class="full-width" 
			:src="cameraList[cameraIndex].url" 
			@error="handlePlayError"
			autoplay></video>
			
			<view class="bg-white padding flex align-center justify-between " @click="handleToPage('camera',{id:cameraList[cameraIndex].id})">
				<text>{{cameraList[cameraIndex].name}}</text>
				<van-icon name="arrow-down" custom-style="transform: rotate(-90deg)" />
			</view>
		</view>

		<view class="cu-card case padding-sm">
			<view class="grid col-3 no-border bg-white padding-tb-sm padding-lr">
				<view class="padding-bottom">
					<view class="text-lg text-bold">
						<text>{{pondSelect.offspringSeedName || '未养殖'}}</text>
					</view>
					<text class="text-gray">品种</text>
				</view>
				<view class="">
					<view class="text-lg">
						<text class="text-bold">{{pondSelect.area || '-'}}</text>
						<text class="text-df padding-left-xs">亩</text>
					</view>
					<text class="text-gray">面积</text>
				</view>
				<view class="">
					<view class="text-lg">
						<text class="text-bold">{{pondSelect.typeName || '-'}}</text>
						<text class="text-df padding-left-xs"></text>
					</view>
					<text class="text-gray">类型</text>
				</view>
				<view class="">
					<view class="text-lg">
						<text class="text-bold">{{pondSelect.breedDays || '-'}}</text>
						<text class="text-df padding-left-xs">天</text>
					</view>
					<text class="text-gray">养殖</text>
				</view>
				<view class="">
					<view class="text-lg">
						<text class="text-bold">{{pondSelect.todayUsedFeed || '-'}}</text>
						<text class="text-df padding-left-xs">{{pondSelect.usedFeedUnit}}</text>
					</view>
					<text class="text-gray">今日投喂</text>
				</view>
				<view class="">
					<view class="text-lg">
						<text class="text-bold">{{pondSelect.usedFeed || '-'}}</text>
						<text class="text-df padding-left-xs">{{pondSelect.usedFeedUnit}}</text>
					</view>
					<text class="text-gray">总投喂</text>
				</view>
			</view>
		</view>
		<view class="padding-lr-sm padding-bottom-xs text-gray text-sm">
			<text class="text-red">*&nbsp;</text>
			<text>监测数据更新频率：30s</text>
		</view>
		<view class="padding-lr-sm flex justify-between flex-wrap">
			<view class="bg-white radius padding-sm margin-bottom-sm flex align-center" style="width: 49%;"
				v-for="(item,index) in monitoringList" :key="index">
				<!-- 	<view class="shrink-0 padding-right-sm flex flex-direction align-center">
					<img src="" alt="" class="cu-avatar bg-gray round sm" />
					<text class="padding-top-xs text-sm">{{item.unit}}</text>
				</view> -->
				<view class="" @click="handleToPage('data',{deviceId:item.id})">
					<text class="text-gray">{{item.name}}</text>
					<view class="padding-top-xs">
						<text class="text-xxl text-bold text-black"
							:style="{'color':'#333'}">
							<template v-if="item.type==='WD'">
								{{item.lastData?item.lastData.value+' ℃':'-'}}
							 </template>
							 <template v-if="item.type==='PH'">
								{{item.lastData?item.lastData.value+' mg/L':'-'}}
							 </template>
							 <template v-if="item.type==='YXSY'">
								{{item.lastData?item.lastData.value+' mg/L':'-'}}
							 </template>
							 <template v-if="item.type==='RJYND'">
								{{item.lastData?item.lastData.value+' mg/L':'-'}}
							 </template>
							 <template v-if="item.type==='RJYBHD'">
								{{item.lastData?item.lastData.value+' %':'-'}}
							 </template>
						</text>
						
					</view>
				</view>
			</view>
		</view>
		<view class="padding-lr-sm">
			<template v-for="item in deviceList">
				<view class="flex bg-white padding" @click="handleToPage('ptz',{deviceId:item.id})">
					<view class="shrink-0 padding-right-sm">
						<image :src="getImgUrl(item.fileUrls)" alt="" class="cu-avatar lg bg-gray round" />
						<view class="text-center padding-top-xs">{{item.name}}</view>
					</view>
					<view class="">
						<view class="">
							<text v-if="item.lastData">{{item.lastData.value===1?'运行中':'已停止'}}</text>
							<text v-else>已停止</text>
						</view>
						<view class="">
							<text class="text-gray">今日启动/运行：{{item.runCount}}</text>
						</view>
						<view class="">
							<text class="text-gray">上一次启动：{{item.lastRun?item.lastRun.startTime:'-'}}</text>
						</view>
					</view>
				</view>
			</template>
		</view>
	</view>
</template>

<script>
	import appConfig from '@/config'
	import {
		listSelect,
		getPlayUrl
	} from '@/api/mine/pond'
	
	import {
		getCameraDevice,
		getPondDeviceByCategory
	} from '@/api/mine/equipment'
	
	import {
		monitoringFactors
	} from '@/api/source'
	import {
		mapState
	} from 'vuex'
	export default {
		name: "",
		data() {
			return {
				list: [],
				pondId: undefined,
				pondName: undefined,
				pondSelect: {},
				queryParams: {
					productionBaseId: undefined,
					pondId:undefined
				},
				monitoringList: [],
				interval: null,
				menuHeight: getApp().globalData.menuHeight,
				url:'',
				keepLiveInterval:null,
				deviceList:[],
				cameraList:[],
				cameraIndex:0,
				videoContext:null
			}
		},
		onLoad() {

		},
		onUnload() {
			uni.$off('pondSelect', this.receivePondSelect)
			this.clearInterval()
			
		},
		onShow() {
			// this.handleSetInterval(3000)
			this.queryParams.productionBaseId = this.$store.state.user.baseInfo.id
			this.queryParams.pondId = this.pondSelect.culturePondId
			this.getList()
			if(!this.videoContext){
				this.videoContext = uni.createVideoContext("player");
			}
			// if(this.videoContext){
			// 	this.videoContext.play()
			// }
			console.log(this.videoContext)
		},
		onHide() {
			this.clearInterval()
			// if(this.videoContext){
			// 	this.videoContext.pause()
			// }
			
		},
		computed: {
			...mapState({
				baseInfo: state => state.user.baseInfo
			})
		},
		methods: {
			handlePlayError(e){
				console.log("视频播放异常...",e)
			},
			statechange(e){
				console.log('live-player code:', e.detail.code)
			},
			getCamera(){
				getCameraDevice({pondId:this.pondSelect.culturePondId,protocol:"FLV",type:""})
				.then(res=>{
					this.cameraList = res.data
					this.cameraList.forEach(item=>{
						item.url = item.url.replace("https://cvr.shudatech.cn/","http://39.108.95.19:18000/")
					})
				})
			},
			getImgUrl(url){
				if(!url){
					return ''
				}
				return url.split(",")[0]
			},
			getPondDeviceByCategory(){
				getPondDeviceByCategory({pondId:this.pondSelect.culturePondId,category:'YZSB'})
				.then(res=>{
					this.deviceList = res.data
				})
			},
			clearInterval(){
				if(this.keepLiveInterval){
					clearInterval(this.keepLiveInterval)
					this.keepLiveInterval = null
				}
				if (this.interval) {
					clearInterval(this.interval)
					this.interval = null
				}
			},
			 statechange(e){
				console.log('live-player code:', e.detail.code)
			},
			error(e){
				console.error('live-player error:', e.detail.errMsg)
			},
			handleSetInterval(interval = 50000) {
				if (this.interval) {
					clearInterval(this.interval)
					this.interval = null
				}
				this.interval = setInterval(() => {
					this.getMonitoringFactors()
				}, interval)
			},
			//获取直播地址
			getPlayUrl(){
				getPlayUrl({id:this.pondSelect.culturePondId,protocol:"HLS",type:"keeplive"}).then(res=>{
					this.url = res.data.replace("https://cvr.shudatech.cn/","http://39.108.95.19:18000/")
					console.log(this.url)
					if(this.keepLiveInterval){
						clearInterval(this.keepLiveInterval)
						this.keepLiveInterval = null
					}
					//保活视频流
					this.keepLiveInterval = setInterval(()=>{
						getPlayUrl({id:this.pondSelect.culturePondId,protocol:"HLS",type:"keeplive"})
					},1000*25)
				})
			},
			// 获取设备检测数据
			getMonitoringFactors() {
				this.getPlayUrl()
				this.getPondDeviceByCategory()
				
				getPondDeviceByCategory({pondId:this.pondSelect.culturePondId,category:'JCSB'})
				.then(res=>{
					this.monitoringList = res.data
					if (!this.interval) {
						this.handleSetInterval()
					}
				})
			},
			getList() {
				listSelect(this.queryParams).then(res => {
					this.list = res.rows
					if (this.list.length) {
						let pondSelect = uni.getStorageSync('pondSelect')
						if (pondSelect && JSON.stringify(pondSelect) !== '{}') {
							this.pondSelect = pondSelect
						} else {
							this.pondSelect = this.list[0]
							uni.setStorageSync('pondSelect', this.pondSelect)
						}
						this.getMonitoringFactors()
						this.getCamera()
					} else {
						this.pondSelect = {}
						uni.removeStorageSync('pondSelect')
					}
				})
			},
			receivePondSelect(selection) {
				if (selection.length === 0) return
				this.pondSelect = selection[0]
				
				this.getMonitoringFactors()
				this.getCamera()
				uni.setStorageSync('pondSelect', this.pondSelect)
			},
			handleOpenPondSelect() {
				uni.$on('pondSelect', this.receivePondSelect)
				this.$tab.navigateTo('/pages/mine/pond/select?pondId=' + this.pondSelect.culturePondId)
			},
			handleToPage(path, params) {
				switch (path) {
					case 'camera':
						this.$tab.navigateTo('/pages/source/camera/index?deviceId=' + params.id+"&pondId="+this.pondSelect.culturePondId)
						break;
					case 'data':
						this.$tab.navigateTo('/pages/source/devicedata/index?deviceId=' + params.deviceId+"&pondId="+this.pondSelect.culturePondId)
						break;
					case 'ptz':
					this.$tab.navigateTo('/pages/source/device/index?deviceId=' + params.deviceId+"&pondId="+this.pondSelect.culturePondId)
						break
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	.container {
		.header {
			position: sticky;
			top: 0;
			width: 100%;
			z-index: 999;
		}
	}
</style>